package com.dtw.ditouwang.ui.login;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dtw.ditouwang.BuildConfig;
import com.dtw.ditouwang.R;
import com.dtw.ditouwang.beans.CommonBean;
import com.dtw.ditouwang.beans.SetUserHeadBackBean;
import com.dtw.ditouwang.beans.UserBean;
import com.dtw.ditouwang.beans.WechatUserBean;
import com.dtw.ditouwang.repositories.UserRepository;
import com.dtw.ditouwang.ui.BaseActivity;
import com.dtw.ditouwang.ui.main.MainActivity;
import com.dtw.ditouwang.utils.FileUtils;
import com.dtw.ditouwang.utils.SharedPreferencesUtil;

import java.io.File;

import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.wechat.Wechat;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    /**
     * 登陆
     */
    private RadioButton radioLogin;
    /**
     * 注册
     */
    private RadioButton radioRegist;
    /**
     * 请输入11位手机号
     */
    private EditText phone;
    /**
     * 请输入验证码
     */
    private EditText textCode;
    /**
     * 获取验证码
     */
    private TextView textGetcode;
    /**
     * 请输入邀请码(选填)
     */
    private EditText textInviteCode;
    /**
     * 登录
     */
    private Button buttonLogin;
    private ImageView imgLoginWechat;
    private ImageView imgLoginWeibo;
    TextView loginType, forgetPass;
    CountDownTimer countDownTimer;
    boolean hashead = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setContentView(R.layout.activity_login);
        initView();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        }
        if (sharedPreferencesUtil.getLoginType() != SharedPreferencesUtil.LoginType.Null) {
            UserRepository.getInstance().setUserBean(sharedPreferencesUtil.getBean(UserBean.class));
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                textGetcode.setText(millisUntilFinished / 1000 + " s");
            }

            @Override
            public void onFinish() {
                textGetcode.setText("获取验证码");
                textGetcode.setEnabled(true);
            }
        };
    }

    private void initView() {
        radioLogin = findViewById(R.id.radio_login);
        radioRegist = findViewById(R.id.radio_regist);
        loginType = findViewById(R.id.text_logintype);
        forgetPass = findViewById(R.id.text_forget_pass);
        phone = findViewById(R.id.phone);
        textCode = findViewById(R.id.text_code);
        textGetcode = findViewById(R.id.text_getcode);
        textGetcode.setOnClickListener(this);
        textInviteCode = findViewById(R.id.text_invite_code);
        buttonLogin = findViewById(R.id.button_login);
        buttonLogin.setOnClickListener(this);
        imgLoginWechat = findViewById(R.id.img_login_wechat);
        imgLoginWeibo = findViewById(R.id.img_login_weibo);
        radioLogin.setOnCheckedChangeListener(this);
        radioRegist.setOnCheckedChangeListener(this);
        loginType.setOnClickListener(this);
        forgetPass.setOnClickListener(this);
        radioLogin.setChecked(true);
        imgLoginWechat.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.text_getcode:
                countDownTimer.start();
                textGetcode.setEnabled(false);
                int codeType = 1;
                if (radioLogin.isChecked()) {
                    codeType = 2;
                }
                webApi.getCode(phone.getText().toString(), codeType).enqueue(new Callback<CommonBean>() {
                    @Override
                    public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                        if (response.body().isResult()) {
                            showToast("验证码发送成功");
                        } else {
                            showToast(response.body().getMsg());
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonBean> call, Throwable t) {

                    }
                });
                break;
            case R.id.button_login:
                showProgress();
                if (radioLogin.isChecked()) {
                    if (!loginType.getText().toString().equals("密码登录")) {
                        loginByPass(phone.getText().toString(), textCode.getText().toString());
                    } else {
                        webApi.login(3, phone.getText().toString(), null, textCode.getText().toString()).enqueue(new Callback<UserBean>() {
                            @Override
                            public void onResponse(Call<UserBean> call, final Response<UserBean> responselogin) {
                                closeProgress();
                                if (responselogin.body().isResult()) {
                                    if (TextUtils.isEmpty(responselogin.body().getData().getPassword())) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, R.style.Dialog);
                                        View view = LayoutInflater.from(LoginActivity.this).inflate(R.layout.dialog_create_password, null);
                                        final EditText paw = view.findViewById(R.id.edit_pass);
                                        final EditText pawAgain = view.findViewById(R.id.edit_pass_again);
                                        View confirm = view.findViewById(R.id.text_confirm);
                                        builder.setView(view);

                                        final AlertDialog alertDialog = builder.create();
                                        confirm.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (!paw.getText().toString().isEmpty() && paw.getText().toString().equals(pawAgain.getText().toString())) {
                                                    webApi.updatePass(phone.getText().toString(), paw.getText().toString()).enqueue(new Callback<CommonBean>() {
                                                        @Override
                                                        public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                                                            if (response.body().isResult()) {
                                                                showToast("设置密码成功");
                                                                alertDialog.dismiss();
                                                                UserRepository.getInstance().setUserBean(responselogin.body());
                                                                sharedPreferencesUtil.setUserName(phone.getText().toString());
                                                                sharedPreferencesUtil.setUserPassword(textCode.getText().toString());
                                                                sharedPreferencesUtil.setLoginType(SharedPreferencesUtil.LoginType.Phone);
                                                                sharedPreferencesUtil.setBean(response.body());
                                                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                                                LoginActivity.this.finish();
                                                            } else {
                                                                showToast(response.body().getMsg());
                                                            }
                                                        }

                                                        @Override
                                                        public void onFailure(Call<CommonBean> call, Throwable t) {
                                                            showToast("失败");
                                                            alertDialog.dismiss();
                                                        }
                                                    });
                                                } else {
                                                    showToast("密码不能为空，且两次输入必须一致");
                                                }
                                            }
                                        });
                                        alertDialog.setCancelable(false);
                                        alertDialog.show();
                                    } else {
                                        UserRepository.getInstance().setUserBean(responselogin.body());
                                        sharedPreferencesUtil.setUserName(phone.getText().toString());
                                        sharedPreferencesUtil.setUserPassword(textCode.getText().toString());
                                        sharedPreferencesUtil.setLoginType(SharedPreferencesUtil.LoginType.Phone);
                                        sharedPreferencesUtil.setBean(responselogin.body());
                                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                        finish();
                                    }
                                } else {
                                    showToast(responselogin.body().getMsg());
                                }
                            }

                            @Override
                            public void onFailure(Call<UserBean> call, Throwable t) {
                                Log.i("dtw", "dtw");
                            }
                        });
                    }
                } else {
                    webApi.regist(0, phone.getText().toString(), "123456", null, null, null, null, null, textCode.getText().toString()).enqueue(new Callback<UserBean>() {
                        @Override
                        public void onResponse(Call<UserBean> call, final Response<UserBean> responseregist) {
                            closeProgress();
                            if (responseregist.body().isResult()) {
//                                if (TextUtils.isEmpty(responseregist.body().getData().getPassword())) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, R.style.Dialog);
                                View view = LayoutInflater.from(LoginActivity.this).inflate(R.layout.dialog_create_password, null);
                                final EditText paw = view.findViewById(R.id.edit_pass);
                                final EditText pawAgain = view.findViewById(R.id.edit_pass_again);
                                View confirm = view.findViewById(R.id.text_confirm);
                                builder.setView(view);

                                final AlertDialog alertDialog = builder.create();
                                confirm.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (!paw.getText().toString().isEmpty() && paw.getText().toString().equals(pawAgain.getText().toString())) {
                                            webApi.updatePass(phone.getText().toString(), paw.getText().toString()).enqueue(new Callback<CommonBean>() {
                                                @Override
                                                public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                                                    if (response.body().isResult()) {
                                                        showToast("设置密码成功");
                                                        alertDialog.dismiss();
                                                        UserRepository.getInstance().setUserBean(responseregist.body());
                                                        sharedPreferencesUtil.setUserName(phone.getText().toString());
                                                        sharedPreferencesUtil.setUserPassword(paw.getText().toString());
                                                        sharedPreferencesUtil.setLoginType(SharedPreferencesUtil.LoginType.Phone);
                                                        sharedPreferencesUtil.setBean(response.body());
                                                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                                        LoginActivity.this.finish();
                                                    } else {
                                                        showToast(response.body().getMsg());
                                                    }
                                                }

                                                @Override
                                                public void onFailure(Call<CommonBean> call, Throwable t) {
                                                    showToast("失败");
                                                    alertDialog.dismiss();
                                                }
                                            });
                                        } else {
                                            showToast("密码不能为空，且两次输入必须一致");
                                        }
                                    }
                                });
                                alertDialog.setCancelable(false);
                                alertDialog.show();
//                                } else {
//                                    UserRepository.getInstance().setUserBean(responseregist.body());
//                                    sharedPreferencesUtil.setUserName(phone.getText().toString());
//                                    sharedPreferencesUtil.setUserPassword(textCode.getText().toString());
//                                    sharedPreferencesUtil.setBean(responseregist.body());
//                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                                    finish();
//                                }
                            } else {
                                showToast(responseregist.body().getMsg());
                            }
                        }

                        @Override
                        public void onFailure(Call<UserBean> call, Throwable t) {

                        }
                    });
                }
                break;
            case R.id.text_logintype:
                if (loginType.getText().equals("密码登录")) {
                    loginType.setText("手机验证码登陆");
                    textGetcode.setVisibility(View.INVISIBLE);
                    textCode.setHint("请输入密码");
                    textCode.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    textCode.setText(null);

                } else {
                    loginType.setText("密码登录");
                    textGetcode.setVisibility(View.VISIBLE);
                    textCode.setHint("获取验证码");
                    textCode.setInputType(InputType.TYPE_CLASS_TEXT);
                    textCode.setText(null);
                }
                break;
            case R.id.text_forget_pass:
                startActivity(new Intent(this, ForgetPasswordActivity.class));
                break;
            case R.id.img_login_wechat:
                if (BuildConfig.DEBUG) {
                    weichatLogin("test"+System.currentTimeMillis(), "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555662309282&di=0beed802f4ad22b877d08e5fb58ffa4f&imgtype=0&src=http%3A%2F%2Fcdnq.duitang.com%2Fuploads%2Fitem%2F201409%2F20%2F20140920224243_FGURS.thumb.700_0.png"
                            , "nickname");
                } else {
                    JShareInterface.authorize(Wechat.Name, new AuthListener() {
                        @Override
                        public void onComplete(Platform platform, int i, BaseResponseInfo baseResponseInfo) {
                            Log.i("dtw", "onComplete:" + platform);
                            webApi.getWechatUserInfo(((AccessTokenInfo) baseResponseInfo).getToken(), ((AccessTokenInfo) baseResponseInfo).getOpenid()).enqueue(new Callback<WechatUserBean>() {
                                @Override
                                public void onResponse(Call<WechatUserBean> call, final Response<WechatUserBean> responses) {
                                    Log.i("dtw", responses.body().toString());
                                    weichatLogin(responses.body().getOpenid(), responses.body().getHeadimgurl(), responses.body().getNickname());
                                }

                                @Override
                                public void onFailure(Call<WechatUserBean> call, Throwable t) {
                                    showToast("登录失败");
                                    finish();
                                }
                            });
                        }

                        @Override
                        public void onError(Platform platform, int i, int i1, Throwable throwable) {
                            Log.i("dtw", "onError:" + platform);

                        }

                        @Override
                        public void onCancel(Platform platform, int i) {
                            Log.i("dtw", "onCancel:" + platform);

                        }
                    });
                }
                break;
        }
    }

    private void loginByPass(final String phone, final String pass) {
        webApi.login(0, phone, pass, null).enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                closeProgress();
                if (response.body().isResult()) {
                    sharedPreferencesUtil.setBean(response.body());
                    UserRepository.getInstance().setUserBean(response.body());
                    sharedPreferencesUtil.setUserName(phone);
                    sharedPreferencesUtil.setUserPassword(pass);
                    sharedPreferencesUtil.setBean(response.body());
                    sharedPreferencesUtil.setLoginType(SharedPreferencesUtil.LoginType.Phone);
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();

                } else {
                    showToast(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                Log.i("dtw", "dtw");
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.radio_login:
                    buttonLogin.setText("登录");
                    loginType.setVisibility(View.VISIBLE);
                    loginType.setClickable(true);
                    textGetcode.setVisibility(View.INVISIBLE);
                    textInviteCode.setVisibility(View.INVISIBLE);
                    textCode.setHint("请输入密码");
                    loginType.setText("手机验证码登陆");
                    textCode.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    phone.setText(sharedPreferencesUtil.getUserName());
                    textCode.setText(sharedPreferencesUtil.getPassword());
                    textCode.setText(null);
                    break;
                case R.id.radio_regist:
                    buttonLogin.setText("注册");
                    loginType.setVisibility(View.INVISIBLE);
                    loginType.setClickable(false);
                    textGetcode.setVisibility(View.VISIBLE);
                    textInviteCode.setVisibility(View.VISIBLE);
                    textCode.setHint("获取验证码");
                    textCode.setInputType(InputType.TYPE_CLASS_TEXT);
                    phone.setText(null);
                    textCode.setText(null);
                    break;
            }
        }
    }

    private void uploadUserHead(File imagefile) {
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imagefile);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("imghaed", imagefile.getName(), requestFile);

        webApi.uploadHead(filePart).enqueue(new Callback<CommonBean>() {
            @Override
            public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                if (response.body().isResult() && response.body().getData() != null) {
                    UserRepository.getInstance().getUserBean().getData().setHead((String) response.body().getData());
                    setUserHead(UserRepository.getInstance().getUserID(), (String) response.body().getData());
                } else {
                    showToast(response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<CommonBean> call, Throwable t) {

            }
        });
    }

    private void setUserHead(int userID, String imagePath) {
        webApi.setUserHead(userID, imagePath).enqueue(new Callback<SetUserHeadBackBean>() {
            @Override
            public void onResponse(Call<SetUserHeadBackBean> call, Response<SetUserHeadBackBean> response) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                LoginActivity.this.finish();
            }

            @Override
            public void onFailure(Call<SetUserHeadBackBean> call, Throwable t) {

            }
        });
    }

    private void weichatLogin(final String openid, final String headImgUrl, final String nickName) {
        webApi.login(2, openid, null, null).enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                UserRepository.getInstance().setUserBean(response.body());
                sharedPreferencesUtil.setUserName(openid);
                sharedPreferencesUtil.setUserPassword(null);
                sharedPreferencesUtil.setLoginType(SharedPreferencesUtil.LoginType.Wechat);
                sharedPreferencesUtil.setBean(response.body());
                if (TextUtils.isEmpty(response.body().getData().getHead())) {
                    hashead = false;
                    webApi.downloadFile(headImgUrl).enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response.isSuccessful()) {
                                File imageFile = FileUtils.writeFileToSDCard(LoginActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), response.body());
                                if (imageFile != null) {
                                    uploadUserHead(imageFile);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                }
                if (TextUtils.isEmpty(response.body().getData().getNickname())) {
                    webApi.setUserInfo(response.body().getData().getId(), response.body().getData().getName(), response.body().getData().getBirthdate(),
                            Integer.parseInt(response.body().getData().getSex()==null?"1":response.body().getData().getSex()), response.body().getData().getAge(), nickName,
                            response.body().getData().getHobby(), response.body().getData().getAddress(), response.body().getData().getStature(), response.body().getData().getConstellation()).enqueue(new Callback<CommonBean>() {
                        @Override
                        public void onResponse(Call<CommonBean> call, Response<CommonBean> response) {
                            if (hashead) {
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                LoginActivity.this.finish();
                            }
                        }

                        @Override
                        public void onFailure(Call<CommonBean> call, Throwable t) {
                            showToast("网络异常");
                        }
                    });
                }
                if (!TextUtils.isEmpty(response.body().getData().getHead()) && !TextUtils.isEmpty(response.body().getData().getNickname())) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    LoginActivity.this.finish();
                }
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {

            }
        });
    }
}
